<template>
  <el-dialog
    title="实体卡签到"
    class="gl_dialog_TitleLine gl_dl_footer"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    :before-close="cancelDialog"
    width="800px"
  >
    <div :class="['outer', bindStatus === 'knownCard' ? 'outer_padding' : '']">
      <div v-if="bindStatus === 'knownCard' && showMsg === 'success'" class="showMsg success">签到成功</div>
      <div v-if="bindStatus === 'knownCard' && showMsg === 'noCourse'" class="showMsg noCourse">暂无可签到课程</div>
      <div v-if="bindStatus === 'noCard'" class="no_card">请将会员卡置于读卡器处</div>
      <div v-if="bindStatus === 'cardError'" class="no_card errorMsg">{{ errorMsg }}</div>
      <div v-if="bindStatus === 'knownCard'" class="no_card">
        <div class="item">
          <div class="label">会员卡：</div>
          <div class="content">{{ studentInfo.cardNumber || '' }}</div>
        </div>
        <div class="item">
          <div class="label">学生姓名：</div>
          <div class="content">{{ studentInfo.name || '' }}</div>
        </div>
        <div class="item">
          <div class="label">签到课程：</div>
          <div v-if="courseList.length > 0" class="courses">
            <div v-for="(item, index) in courseList" :key="index" class="list">
              <div class="courseName"><el-radio v-model="selectedCourse" :disabled="!!(item.checkInTime)" :label="item.courseScheduleId"><span class="name">{{ item.className + '_' + item.courseName }}</span></el-radio></div>
              <!--<div v-else class="courseName"><el-radio v-model="selectedCourse" :disabled="item.checkInTime" :label="item.id"><span class="name">{{ item.name }}</span></el-radio></div>-->
              <div v-if="item.checkInTime" class="checkInTime">{{ item.checkInTime | FormatDate('yyyy-MM-dd') }} {{ item.checkInTime | FormatDate('HH:mm') }}</div>
            </div>
          </div>
          <div v-else class="content">暂无课程</div>
        </div>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button v-if="bindStatus === 'knownCard' && unSignInList.length > 1" size="mini" type="primary" :loading="cancelLoading" @click="cancel()">取 消</el-button>
      <el-button v-if="bindStatus === 'knownCard' && unSignInList.length > 1" size="mini" type="primary" :loading="btnLoading" @click="signIn()">签 到</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  api_GET_ClubClubSecretKey, // 获取密钥
  api_GET_ClubClubCardStudentSearchCardStudent // 依据实体卡号查询学员及课程
} from '@/extend/api/hall.js';
import { api_POST_ClubCheckInLogCheckIn } from '@/extend/api/hallswaggerApi/app.js';
import axios from 'axios';
export default {
  data () {
    return {
      bindStatus: 'noCard',
      dialogVisible: false,
      btnLoading: false,
      courseList: [],
      unSignInList: [],
      selectedCourse: '',
      secretKey: '',
      errorMsg: '',
      studentInfo: {},
      showMsg: '',
      cardSN: '',
      physicalCardId: '',
      reading: false,
      cancelLoading: false,
      timer: null
    };
  },
  watch: {
    'physicalCardId': {
      immediate: true,
      deep: true,
      handler(val, old) {
        if (val) {
          this.getKnownCardInfo(val);
        }
      }
    }
  },
  methods: {
    init() {
      this.getSecretKey().then((res) => {
        this.secretKey = res.secretKey;
        this.readCardsn();
      });
    },
    // 1.获取密钥
    getSecretKey() {
      return new Promise((resolve, reject) => {
        api_GET_ClubClubSecretKey().then(res => {
          resolve(res);
        }, error => {
          this.$message({ type: 'error', message: '获取道馆密钥失败！' });
          reject(error);
        });
      });
    },
    readCardsn() {
      if (!this.dialogVisible) {
        return false;
      }
      this.reading = true;
      const that = this;
      axios
        .post('http://localhost:36881/M1/Getsnr', {
          mode: 38,
          halt: 0
        })
        .then((res) => {
          that.cancelLoading = false;
          if (res && res.data && res.data.Status === 1) {
            // 读取失败;
            that.bindStatus = 'noCard';
            that.cardSN = '';
            that.showMsg = '';
            that.physicalCardId = '';
            setTimeout(() => {
              that.readCardsn();
            }, 1000);
          } else if (res && res.data && res.data.Status === 0) {
            if (that.cardSN === res.data.card_sn) {
              setTimeout(() => {
                that.readCardsn();
              }, 1000);
            } else {
              that.controlBuzzer().then(() => {
                that.showMsg = '';
                that.cardSN = res.data.card_sn;
                that.readCardData();
              });
            }
          } else {
            that.getError(res);
          }
        }, error => {
          const _msg = error.message === 'Network Error' ? '网络错误，请前往实体卡管理页面下载读卡服务，安装后重试！' : error.message;
          that.$message({ type: 'error', message: _msg });
        });
    },
    // 2.读卡数据--并根据读卡结果做相应操作
    readCardData() {
      if (!(this.secretKey && this.secretKey.length === 12)) {
        this.$message({ type: 'error', message: '获取道馆密钥失败，无法读取卡片！' });
        return false;
      }
      const that = this;
      axios
        .post('http://localhost:36881/M1/Read', {
          inf_mode: 0,
          blk_add: 4,
          num_blk: 1,
          card_password: that.secretKey
        })
        .then((res) => {
          if (res && res.data && res.data.Status === 1) {
            // 未读取成功----------不能识别此卡片-----重读
            that.physicalCardId = '';
            that.bindStatus = 'cardError';
            that.errorMsg = '无法识别卡片，请重试';
            setTimeout(() => {
              that.bindStatus = 'noCard';
              that.reRead();
            }, 2000);
          } else if (res && res.data && res.data.Status === 0) {
            // 读取成功----------非白卡-----修改状态---获取卡片信息对应学生信息
            that.physicalCardId = res.data.data;
          } else {
            that.getError(res);
          }
        }, error => {
          const _msg = error.message === 'Network Error' ? '网络错误，请前往实体卡管理页面下载读卡服务，安装后重试！' : error.message;
          that.$message({ type: 'error', message: _msg });
        });
    },
    // 根据卡片编号获取绑定信息--课程信息
    getKnownCardInfo(data) {
      const that = this;
      const qo = { cardNumber: data };
      api_GET_ClubClubCardStudentSearchCardStudent(qo).then(res => {
        // 多节课 默认选中 展示签到按钮 签到接口 成功展示签到成功 2s后重读   | 签到失败   2s后重读
        this.bindStatus = 'knownCard';
        this.courseList = res.courses || [];
        that.studentInfo = {
          id: res.student.id,
          name: res.student.name,
          cardNumber: res.clubCard.cardNumber
        };
        that.unSignInList = [];
        that.courseList.forEach((item, index) => {
          if (!item.checkInTime) {
            that.unSignInList.push(item);
          }
        });
        if (that.unSignInList.length > 1) {
          that.selectedCourse = that.unSignInList[0].courseScheduleId;
          this.reading = false;
        } else if (that.unSignInList.length === 1) {
          that.selectedCourse = that.unSignInList[0].courseScheduleId;
          that.signIn();
        } else {
          // 暂无可签到课程
          that.showMsg = 'noCourse';
          setTimeout(() => {
            // that.bindStatus = 'noCard';
            that.reRead();
          }, 2000);
        }
      }, error => {
        this.bindStatus = 'cardError';
        this.errorMsg = error.error.message || error.message;
        setTimeout(() => {
          that.reRead();
        }, 2000);
      });
    },
    signIn() {
      const qo = {
        studentId: this.studentInfo.id,
        courseScheduleId: this.selectedCourse
      };
      const that = this;
      this.btnLoading = true;
      api_POST_ClubCheckInLogCheckIn(qo).then(res => {
        that.btnLoading = false;
        that.showMsg = 'success';
        setTimeout(() => {
          that.reRead();
        }, 2000);
      }, error => {
        that.btnLoading = false;
        this.bindStatus = 'cardError';
        this.errorMsg = error.error.message || error.message;
        setTimeout(() => {
          that.reRead();
        }, 2000);
      });
    },
    confirm() {
      this.signIn();
    },
    reRead() {
      const that = this;
      setTimeout(() => {
        // that.showMsg = '';
        that.readCardsn();
      }, 1000);
    },
    getError(res) {
      const that = this;
      if (res && res.data && res.data.Status === 800018) {
        that.$message({ type: 'error', message: '读卡设备不存在，请连接后重试！' });
      } else if (res && res.data && res.data.Status === 90001) {
        that.$message({ type: 'error', message: '缺少必要参数，请重试！' });
      } else {
        that.$message({ type: 'error', message: res.data && res.data.Msg });
      }
    },
    cancel() {
      const that = this;
      this.cancelLoading = true;
      this.timer ? clearTimeout(this.timer) : '';
      this.timer = setTimeout(() => {
        this.cancelLoading = false;
        that.readCardsn();
      }, 500);
    },
    cancelDialog() {
      this.dialogVisible = false;
      this.courseList = [];
      this.bindStatus = 'noCard';
      this.$emit('getList');
    },
    controlBuzzer() {
      const that = this;
      return new Promise((resolve, reject) => {
        axios
          .post('http://localhost:36881/M1/ControlBuzzer', {
            freq: 18,
            duration: 1
          })
          .then((res) => {
            if (res && res.data && res.data.Status === 0) {
              console.log('-------蜂鸣器');
            } else if (res && res.data && res.data.Status === 1) {
              that.$message({ type: 'error', message: res.data.Msg });
            } else {
              that.getError(res);
            }
            resolve(res);
          }, error => {
            reject(error);
            const _msg = error.message === 'Network Error' ? '网络错误，请安装读卡服务后重试！' : error.message;
            that.$message({ type: 'error', message: _msg });
          });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.outer {
  min-height: 450px;
  box-sizing: border-box;
}
.outer_padding {
  padding: 90px 80px 30px 100px;
}
.showMsg {
  position: absolute;
  top: 70px;
  left: 50%;
  margin-left: -100px;
  width: 200px;
  height: 50px;
  font-size: 20px;
  text-align: center;
  line-height: 50px;
  border-radius: 10px;
  box-sizing: border-box;
}
.success {
  color: #39C508;
  background: #F3FFEF;
  border: 1px solid #fff;
}
.noCourse {
  color: #A2A2A2;;
  background: #F1F1F1;
  border: 1px solid #fff;
}
.no_card {
  height: 100%;
  line-height: 410px;
  font-size: 32px;
  font-weight: bold;
  text-align: center;
  color: #333;
  .item {
    min-height: 70px;
    line-height: normal;
    font-size: 28px;
    text-align: left;
    display: flex;
    align-items: flex-start;
    .label {
      width: 110px;
      font-size: 20px;
      font-weight: bold;
    }
    .content {
      flex: 1;
      font-size: 20px;
      font-weight: normal;
    }
    .courses {
      width: 470px;
      font-size: 18px;
      .list {
        display: flex;
        align-items: center;
        padding: 10px 0px;
        .courseName {
          width: 315px;
          margin-right: 15px;
          .name {
            width: 300px;
            display: inline-block;
            vertical-align: middle;
            font-size: 18px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
        .checkInTime {
          width: 140px;
          font-size: 16px;
          color: #b1b0ad;
        }
      }
    }
  }
}
.errorMsg {
  color: #ff0000;
}
</style>

